package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.AddCart;
import csu.web.mypetstore.domain.Cart;
import csu.web.mypetstore.domain.CartItem;
import csu.web.mypetstore.service.AccountService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Iterator;

public class NewOrderServlet extends HttpServlet {
    private static final String NEW_ORDER_FORM = "/WEB-INF/jsp/order/newOrder.jsp";
    private String Msg;
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        AddCart addCart = (AddCart) session.getAttribute("addCart");
        Account loginAccount = (Account) session.getAttribute("loginAccount");
        AccountService accountService = new AccountService();
        Iterator<CartItem> cartItems = cart.getAllCartItems();


        while (cartItems.hasNext()) {
            CartItem cartItem = (CartItem) cartItems.next();
            String itemId = cartItem.getItem().getItemId();
            try {
                Iterator<CartItem> addCartItems = addCart.getAllCartItems();
                while(addCartItems.hasNext()){
                    CartItem addCartItem = (CartItem) addCartItems.next();
                    if(addCartItem.getItem().getItemId().equals(itemId)){
                        int quantity = 0;
                        cart.setQuantityByItemId(itemId, 0);
                        addCart.setQuantityByItemId(itemId, 0);
                        accountService.ReserveCart(loginAccount,cart);
                        if (quantity < 1) {
                            cartItems.remove();
                            addCartItems.remove();
                        }
                    }
                }

            } catch (Exception e) {}
        }
        session.setAttribute("cart",cart);
        session.setAttribute("addCart", addCart);
        this.Msg = "恭喜您，支付成功!";
        req.setAttribute("NewOrderMsg",this.Msg);
        req.getRequestDispatcher(NEW_ORDER_FORM).forward(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}